// 2025/9/25
// 单词搜索

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param board string字符串vector 
     * @param word string字符串 
     * @return bool布尔型
     */
    vector<string> _board;
    string _word;
    vector<pair<int, int>> dpos = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    bool isValid(int x, int y)
    {
        if(0 <= x && x < _board.size() && 0 <= y && _board[0].size())
            return true;
        return false;
    }

    bool dfs(int i, int j, int pos)
    {
        if(_board[i][j] != _word[pos])
            return false;
        if(pos == _word.size() - 1)
            return true;

        char tmp = _board[i][j];
        _board[i][j] = 0;
        for(auto& pr : dpos)
        {
            int x = i + pr.first, y = j + pr.second;
            if(isValid(x, y) && dfs(x, y, pos + 1))
                return true;
        }
        _board[i][j] = tmp;
        return false;
    }
    
    bool exist(vector<string>& board, string word) {
        // write code here
        int m = board.size(), n = board[0].size();
        _board = board;
        _word = word;
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(board[i][j] == word[0])
                {
                    if(dfs(i, j, 0))
                        return true;
                }
            }
        }
        return false;
    }
};